package fun.stgoder.bmwf.gateway.handler;

import fun.stgoder.bmwf.gateway.util.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();

        if (exchange.getResponse().isCommitted()) {
            return Mono.error(ex);
        }

        String msg;

        HttpStatus httpStatus;
        if (ex instanceof NotFoundException) {
            msg = "服务未找到";
            httpStatus = HttpStatus.NOT_FOUND;
        } else if (ex instanceof ResponseStatusException) {
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;
            msg = responseStatusException.getMessage();
            httpStatus = responseStatusException.getStatus();
        } else {
            msg = "内部服务器错误";
            httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        }

        ex.printStackTrace();
        log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), ex.getMessage());

        return ServletUtil.webFluxResponseWriter(response, MediaType.APPLICATION_JSON_VALUE, httpStatus, msg, httpStatus.value());
    }
}
